import 'package:flutter/material.dart';
import 'package:ileddemo/code/ble/protocol/iledcolor/source/PlayListManager.dart';
import 'package:ileddemo/code/ui/base/BaseWidget.dart';
import 'package:ileddemo/code/ui/base/TitleBarWidget.dart';
import 'package:ileddemo/code/ui/source/ShowSourceWidget.dart';
import 'package:lib_bt/BleManager.dart';
import 'package:lib_bt/send/BleSendManager.dart';
import 'package:lib_bt/send/SendBean.dart';
import 'package:lib_bt/send/MultipleSendBean.dart';
import 'package:lib_util/ByteUtils.dart';

import '../../../generated/l10n.dart';
import '../../ble/protocol/AutoConnectUtil.dart';
import '../../ble/protocol/SendProgressDialogUtil.dart';
import '../../ble/protocol/base/SourceInterface.dart';
import '../../ble/protocol/iledcolor/BleBean.dart';
import '../../ble/protocol/iledcolor/send/ColorPackageImpl.dart';
import '../../ble/protocol/iledcolor/source/ColorSourceInterface.dart';
import '../../ble/protocol/iledcolor/source/partition/PartitionSourceBean.dart';
import 'AddListPage.dart';

class PlayListPage extends StatefulWidget {
  const PlayListPage({super.key});

  @override
  State<PlayListPage> createState() => _PlayListPageState();
}

class _PlayListPageState extends State<PlayListPage> {
  Size getScreenSize() {
    var lastConnectBleBean = AutoConnectUtil.instance.getLastConnectBleBean();
    BleBean bleBean = BleBean(bean: lastConnectBleBean);
    return bleBean.getSize();
  }

  List<ColorSourceInterface> getSourceList() {
    return PlayListManager.instance.getPlayList(getScreenSize());
  }

  @override
  Widget build(BuildContext context) {
    List<ColorSourceInterface> sourceList = getSourceList();
    return BaseWidget(
      child: Column(
        children: [
          TitleBarWidget(
            title: S.of(context).str_id_35,
            rightWidget: [
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () async {
                  var list = await Navigator.of(
                    context,
                  ).push(MaterialPageRoute(builder: (context) => const AddListPage()));
                  if (list != null && list.isNotEmpty) {
                    List<int> l =  [];
                    for (var source in sourceList) {
                      l.add(source.id);
                    }
                    l.addAll(list);

                    PlayListManager.instance.savePlayListForId(l);
                    setState(() {});
                  }
                },
                child: Padding(
                  padding: const EdgeInsets.only(right: 10),
                  child: Icon(size: 30, Icons.control_point_outlined),
                ),
              ),
            ],
          ),

          Expanded(
            child: ListView.builder(
              itemCount: sourceList.length,
              itemBuilder: (BuildContext context, int index) {
                var source = sourceList[index];
                return Stack(
                  fit: StackFit.passthrough,
                  children: [
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                      decoration: BoxDecoration(color: Colors.blueGrey),
                      child: ShowSourceWidget(source: source),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        GestureDetector(
                          behavior: HitTestBehavior.translucent,
                          onTap: () async {
                            sourceList.remove(source);
                            PlayListManager.instance.savePlayList(sourceList);
                            setState(() {});
                          },
                          child: Icon(size: 40, Icons.delete_forever_outlined),
                        ),
                      ],
                    ),
                  ],
                );
              },
            ),
          ),

          //发送按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () async {
                  var bleBeans = BleManager.instance.getConnectBleBeans();
                  if (bleBeans.isEmpty) {
                    return;
                  }
                  List<BleBean> b = [];
                  for (var bleBean in bleBeans) {
                    b.add(BleBean(bean: bleBean));
                  }

                  List<SendBean> sendBeans = [];
                  for (var bleBean in b) {
                    MultipleSendBean multipleSendBean = MultipleSendBean()..address = bleBean.address;
                    for (int i = 0; i < sourceList.length; i++) {
                      SendBean sendBean = SendBean()..address = bleBean.address;
                      PartitionSourceBean partitionSourceBean = sourceList[i].castPartitionSourceBean();
                      List<int> sendData = await partitionSourceBean.getSendData(bleBean);
                      var package = ColorPackageImpl.createSimplePackage(
                        [0x54, 0x03],
                        [sourceList.length, i] +
                            sendData.sublist(0, 4) +
                            ByteUtils.int2Byte(sendData.length) +
                            [1, 0] +
                            [0, 0],
                      );
                      sendBean.addPackage(package);
                      sendBean.addPackages(ColorPackageImpl.createPackage(sendData, bleBean.mtu));
                      multipleSendBean.addSendBean(sendBean);
                    }
                    //列表更新完成的指令
                    SendBean sendBean = SendBean()..address = bleBean.address;
                    var package = ColorPackageImpl.createSimplePackage([0x54, 0x08], [1]);
                    sendBean.addPackage(package);
                    multipleSendBean.addSendBean(sendBean);
                    sendBeans.add(multipleSendBean);
                  }

                  print("开始发送:${sendBeans.length}");
                  SendProgressDialogUtil.instance.showDialog();
                  BleSendManager.instance.send(
                    sendBeans,
                    onError: (msg, data) {
                      print("发送失败");
                      SendProgressDialogUtil.instance.dismissDialog();
                    },
                    onSuccess: (msg, data) {
                      print("发送成功");
                      SendProgressDialogUtil.instance.dismissDialog();
                    },
                  );
                },
                child: Container(
                  decoration: BoxDecoration(color: Colors.blueGrey, borderRadius: BorderRadius.circular(10)),
                  padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 30),
                  child: Text(S.of(context).str_id_4, style: TextStyle(fontSize: 20, color: Colors.black)),
                ),
              ),
            ],
          ),
          const SizedBox(height: 20),
        ],
      ),
    );
  }
}
